﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Localization;
using SinBiota.Model.Business.PersistenceServices.Interfaces;
using SinBiota.Model.Entities;
using Sinbiota.Web.Models;

namespace Sinbiota.Web.Controllers
{
    public class OccurrenceAuthorController : BaseController
    {

        private readonly IOccurrencePersistenceServices _occurrencePersistenceServices;

        public OccurrenceAuthorController(IOccurrencePersistenceServices occurrencePersistenceServices)
        {
            _occurrencePersistenceServices = occurrencePersistenceServices;
        }

        //Get all Authors:
        public JsonResult GetAll()
        {
            const int maxlength = 90;
            var list = _occurrencePersistenceServices.FindAllOccurrenceAuthors().Select(x => new { x.Id, Name = x.Name.Length > maxlength ? x.Name.Substring(0,maxlength) : x.Name }).OrderBy(i => i.Name);
            return Json(list);
        }

        [Authorize]
        public ActionResult Create(OccurrenceAuthor author)
        {
            var newAuthor = new OccurrenceAuthor();
            TryUpdateModel(newAuthor);
            if (ModelState.IsValid)
            {
                _occurrencePersistenceServices.CreateAuthor(newAuthor);
                // If it is an AJAX request (OccurrenceAuthor may be created by AJAX inside other contexts, like Create/Edit Occurrence)
                if (Request != null && Request.IsAjaxRequest()) return Json(JsonMessage.InformationMessage(Messages.OperationCompletedSuccessfully, new { newAuthor.Id }));
                // Normal Action Request:
                SetInformationMessage(Messages.OperationCompletedSuccessfully);
                return RedirectToAction("Index");
            }
            // If it is an AJAX request: 
            if (Request.IsAjaxRequest()) throw new Exception(string.Format("{0}: {1}", Messages.ValidationError, ValidationErrorMessage()));
            return View(newAuthor);

        }
    }
}
